package com.dkd.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dkd.dao.PolicyDao;
import com.dkd.dao.VendingMachineDao;
import com.dkd.entity.PolicyEntity;
import com.dkd.entity.VendingMachineEntity;
import com.dkd.entity.VmPolicyEntity;
import com.dkd.entity.VmTypeEntity;
import com.dkd.entity.dto.ApplyPolicyDto;
import com.dkd.entity.dto.PolicyPageQuery;
import com.dkd.entity.vo.PolicyPageVo;
import com.dkd.entity.vo.VmPolicyDeatilVo;
import com.dkd.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
@RequiredArgsConstructor
public class PolicyServiceImpl extends ServiceImpl<PolicyDao, PolicyEntity> implements PolicyService {
    private final VmPolicyService vmPolicyService;
    private final VendingMachineDao vendingMachineDao;
    private final NodeService nodeService;
    @Override
    public PolicyPageVo getPolicy(PolicyPageQuery policyPageQuery) {
        Integer pageIndex = policyPageQuery.getPageIndex();//页码
        Integer pageSize = policyPageQuery.getPageSize();//页大小
        Page<PolicyEntity> page = new Page<>(pageIndex,pageSize);
        this.lambdaQuery().like(policyPageQuery.getName()!=null,PolicyEntity::getPolicyName,policyPageQuery.getName()).page(page);
        long totalCount = page.getTotal();//总大小
        long totalPage = totalCount / pageSize;//总页数

        List<PolicyEntity> policyEntitys = page.getRecords();//策略列表

        return new PolicyPageVo(pageIndex.toString(),pageSize.toString(),String.valueOf(totalPage),String.valueOf(totalCount),policyEntitys);
    }

    @Override
    public List<VmPolicyDeatilVo> getPolicyById(Integer policyId) {
        List<VmPolicyEntity> VmPolicyEntityList = vmPolicyService.lambdaQuery().eq(VmPolicyEntity::getPolicyId, policyId).list();
        List<VmPolicyDeatilVo> list = new ArrayList<>();
        for (VmPolicyEntity vmPolicyEntity : VmPolicyEntityList) {
            VmPolicyDeatilVo vmPolicyDeatilVo = new VmPolicyDeatilVo();
            BeanUtils.copyProperties(vmPolicyEntity,vmPolicyDeatilVo);

            Long vmId = vmPolicyEntity.getVmId();
            VendingMachineEntity vendingMachineEntity = vendingMachineDao.selectById(vmId);
            if (vendingMachineEntity!=null){
                Long nodeId = vendingMachineEntity.getNodeId();
                vmPolicyDeatilVo.setNodeId(nodeId.intValue());
                vmPolicyDeatilVo.setNodeName( nodeService.getById(nodeId).getName());
                list.add(vmPolicyDeatilVo);
            }
        }

        return list;
    }
}
